<?php

  //much of this is adapted from the o'reilly book web db apps w/ php & mysql

  //check if a user is in the database
  function userExists($loginUsername, $connection) {
	return "yes";
    $query = "SELECT username FROM cdb_users " .
             "WHERE username = '$loginUsername'";

    //echo $query;

    $result = $connection->query($query);

    if (DB::isError($result)) {
        //echo "error";
        //echo $result->getMessage();
        //echo $result->getDebugInfo();

      trigger_error($result->getMessage(), E_USER_ERROR);
    }

    if ($result->numRows() == 0)  {
    //  echo "no";
      return false;
    } else {
    //  echo "yes";
      return true;
    }    
  }

  //Add a new user to the table
  function newUser($loginUsername, $loginPassword, $connection) {
     
     $cryptedPassword = md5(trim($loginPassword));
     
     $query = "INSERT into cdb_users (username, password, admin) " .
              "VALUES ('{$loginUsername}', '{$cryptedPassword}', 'FALSE')";
     
     $result = $connection->query($query);

     if (DB::isError($result)) {
        trigger_error($result->getMessage(), E_USER_ERROR);
     }
  }

  
  //this code is used to check if the username and password collected
  //from the user form are valid for the condorDB user database

  function authenticateUser($loginUsername, $loginPassword, $connection) {
	// for now, as we're removing hte cdb table, just take whatever they
	// send us for a username...
    registerLogin($loginUsername, true);
	return true;

	//
    //test that username and password both set, return false if not
    if (!isset($loginUsername) || !isset($loginPassword)) return false;
    

    $cryptedPassword = md5(trim($loginPassword));

    //formulate the query to find the user
    $query = "SELECT admin FROM cdb_users " . 
             "WHERE username = '$loginUsername' " .
                "AND password = '$cryptedPassword'";

    //execute the query	
    $result = $connection->query($query);
    
    if (DB::isError($result)) {
       trigger_error($result->getMessage(), E_USER_ERROR);
    }
    
    if($result->numRows() == 1) {
      $flagResult = $result->fetchRow();
      $flag = false;
      if((strnatcasecmp($flagResult[0], "TRUE")) === 0) {
        $flag = true;
      }
      registerLogin($loginUsername, $flag);
      return true;
    } else {
      return false;
    }
  }


  function registerLogin($loginUsername, $isAdmin) {
    $_SESSION["loginUsername"] = $loginUsername;
    $_SESSION["loginIP"] = $_SERVER["REMOTE_ADDR"];
    $_SESSION["administrator"] = $isAdmin;
    //$_SESSION["administrator"] = true;
  }

  function unregisterLogin() {
    if (isset($_SESSION["loginUsername"])) {
      unset($_SESSION["loginUsername"]);
    }

    if (isset($_SESSION["loginIP"])) {
      unset($_SESSION["loginIP"]);
    }
  }

  function sessionAuthenticate($destinationScript) {
    //Check if the user hasn't logged in
    if (!isset($_SESSION["loginUsername"])) {
       //This does not identify a session
       $_SESSION["message"] = "You must be logged into the system to access " .
                              "the page you requested.";
                              //"{$_SERVER["REQUEST_URI"]}";
       unregisterLogin();
       header("Location: {$destinationScript}");
       exit;
    }

    //Check IP address to check for session hijacking
    if (isset($_SESSION["loginIP"]) &&
       ($_SESSION["loginIP"] != $_SERVER["REMOTE_ADDR"])) {
       
       $_SESSION["message"] = "You are not authorized to access the URL " .
                              "the page you requested from address " .
                              //"{$_SERVER["REQUEST_URI"]} from address " .
			      "{$_SERVER["REMOTE_ADDR"]}";
       unregisterLogin();
       header("Location: {$destinationScript}");
       exit;
    }
  }

  function adminAuthenticate($destinationScript) {
    //first authenticate the session
    sessionAuthenticate($destinationScript);
    //then check the admin flag
    if (!($_SESSION["administrator"] === true)) {
      //this is not an administrator, so send to the dest script
      header("Location: {$destinationScript}");
      exit;
    }

    //otherwise we're okay...so just return
  }  

?>
